accessid = ''
accesskey = ''
host = ''
policyBase64 = ''
signature = ''
callbackbody = ''
filename = ''
key = ''
expire = 0
g_object_name = ''
g_object_name_type = ''
now = timestamp = Date.parse(new Date()) / 1000;

OSS_MODULE_TEMPLATE = 'template'
OSS_MODULE_APP = 'app'
OSS_MODULE_upload = 'upload'
oss_upload_host = 'http://ossstatic.ndmooc.com/'

template_id = $("#template_id").attr("data-id");

function send_request(){
    var xmlhttp = null;
    if (window.XMLHttpRequest){
        xmlhttp=new XMLHttpRequest();
    }else if (window.ActiveXObject){
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    if (xmlhttp!=null){
        serverUrl = '/oss/auth/token'
        xmlhttp.open("GET", serverUrl, false );
        xmlhttp.send(null);
        return xmlhttp.responseText
    }
    getElementsByName
    {
        window.wxc.xcConfirm("Your browser does not support XMLHTTP.", window.wxc.xcConfirm.typeEnum.error)
    }
};

function check_object_radio() {
    var tt = document.getElementsByName('myradio');
    for (var i = 0; i < tt.length ; i++ )
    {
        if(tt[i].checked)
        {
            g_object_name_type = tt[i].value;
            break;
        }
    }
}

function get_signature(){
    //可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
    now = timestamp = Date.parse(new Date()) / 1000;
    if (expire < now + 3)
    {
        body = send_request()
        var obj = eval ("(" + body + ")");
        host = obj['host']
        policyBase64 = obj['policy']
        accessid = obj['accessid']
        signature = obj['signature']
        expire = parseInt(obj['expire'])
        callbackbody = obj['callback']
        key = obj['dir']
        return true;
    }
    return false;
};

function random_string(len) {
　　len = len || 32;
　　var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
　　var maxPos = chars.length;
　　var pwd = '';
　　for (i = 0; i < len; i++) {
    　　pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

function calculate_object_name(filename){
    suffix = get_suffix(filename)
    app_id = $("#app_id").attr("data-id");
    app_version = $("#app_version").val();
    if(template_id){
        file_name = "t_" + template_id
        OSS_MODULE = OSS_MODULE_TEMPLATE
    }else if(app_id){
        file_name = app_id + '_' + app_version
        OSS_MODULE = OSS_MODULE_APP +'/'+ app_id
    }else{
        file_name = random_string(10)
        OSS_MODULE = OSS_MODULE_upload
    }
    g_object_name = key +'/'+ OSS_MODULE +'/'+ file_name + suffix
    console.info("template_id=" + template_id);
    console.info("app_id=" + app_id);
    console.info("app_version=" + app_version);
    console.info("key=" + key);
    console.info("OSS_MODULE=" + OSS_MODULE);
    console.info("suffix=" + suffix);
    console.info("g_object_name=" + g_object_name)

    return ''
}

function get_uploaded_object_name(filename){
    return g_object_name
}

function set_upload_param(up, filename, ret){
    if (ret == false){
        ret = get_signature()
    }
    g_object_name = key;
    if (filename != '') {
        suffix = get_suffix(filename)
        calculate_object_name(filename)
    }
    new_multipart_params = {
        'key' : g_object_name,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid,
        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
        'callback' : callbackbody,
        'signature': signature,
    };

    up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });

    up.start();
}


function console_lc(status){
    console.log("---lc--");
    console.log(status);
    if(status == false){
    alert("上传文件格式不正确")
    }
}

function upload_file_plupload_to_oss(btn_id, show_id, show_src, types){
    console.info("===upload_file_plupload_to_oss==");
    document.getElementById(show_id).innerHTML = ""
    var uploader = new plupload.Uploader({
        runtimes : 'html5,flash,silverlight,html4',
        browse_button : btn_id,
        //multi_selection: false,
        // container: document.getElementById('container'),
        flash_swf_url : '/static/js/plupload/Moxie.swf',
        silverlight_xap_url : '/static/js/plupload/Moxie.xap',
        url : 'http://oss.aliyuncs.com',

//        filters: {
//            mime_types : [
//            { title : "Image files", extensions : "jpg,jpeg,gif,png,bmp"},
//            { title : "Zip files", extensions : "7z,zip,rar,xls,xlsx,doc,docx,ppt,pptx,pdf,txt,ipa,apk"},
//            ],
//            max_file_size : '60mb', //最大只能上传10mb的文件
//            prevent_duplicates : true //不允许选取重复文件
//        },

        init: {
            PostInit: function() {
                $('#' + show_id).html('');
            },

            FilesAdded: function(up, files) {
                plupload.each(files, function(file) {
                    document.getElementById(show_id).innerHTML +='<div class="up-progress" id="' + file.id + '"><p class="up-progress-p"></p></div>'
                });
                set_upload_param(uploader, '', false);
                return false;
            },
            FileFiltered: function(uploader, file) {
            for (var i in file){
            var list = ['jpg','png']
                if (i == 'name'){
                console.log(i,":",file[i])
                var name = file[i].split('.')[1]
                if(list.toString().indexOf(name) > -1) {
                    console.log(name)
                }else{
                    for (var i in uploader.files) {
                        if (uploader.files[i].id == file.id) {
                            toremove = i;
                        }
                    }
                uploader.files.splice(toremove, 1);
                console_lc(false)
                return false;
                }
                }
            }
            },

            BeforeUpload: function(up, file) {
                set_upload_param(up, file.name, true);
            },

            UploadProgress: function(up, file) {
                $('#' + file.id).find('p').css({'width': file.percent+'%'})
                // setTimeout(function(){$('#' + file.id).remove(), 2000});
            },

            FileUploaded: function(up, file, info) {
                var url = get_uploaded_object_name(file.name)
                console.info("info=" + info)
                console.info("url=" + url)
                if (info.status == 200){
                    if(types == "pic"){
                        $("#" + show_src).attr("src", oss_upload_host + url);
                    }else{
                         $("#" + show_src).html(file.name);
                         $("#" + show_src).attr("data-src", oss_upload_host + url);
                    }

                }
            },

            UploadComplete: function(up, files){
    //            window.wxc.xcConfirm("文件传成功!", window.wxc.xcConfirm.typeEnum.success,{onOk:function(){
    //                window.location.reload();
    //            }});
            },

            Error: function(up, err) {
                if (err.code == -600) {
                    window.wxc.xcConfirm("选择的文件太大了!", window.wxc.xcConfirm.typeEnum.error,{onOk:function(){
                        window.location.reload();
                    }});
                }else if (err.code == -601) {
                    window.wxc.xcConfirm("选择的文件后缀不对!", window.wxc.xcConfirm.typeEnum.error,{onOk:function(){
                        window.location.reload();
                    }});
                }else if (err.code == -602) {
                    window.wxc.xcConfirm("这个文件已经在上传列表中!", window.wxc.xcConfirm.typeEnum.error,{onOk:function(){
                        window.location.reload();
                    }});
                }else{
                    window.wxc.xcConfirm('err-code:' + err.code +';'+  err.response, window.wxc.xcConfirm.typeEnum.error,{onOk:function(){
                        window.location.reload();
                    }});
                }
            }
        }
    });
    uploader.init();
    console.log('333333333333333333')
    console.log(uploader)
    console.log(uploader.FileFiltered)
}


function upload_file_plupload_to_oss_zip(btn_id, show_id, show_src, types){
    console.info("===upload_file_plupload_to_oss==");
    document.getElementById(show_id).innerHTML = ""
    var uploader = new plupload.Uploader({
        runtimes : 'html5,flash,silverlight,html4',
        browse_button : btn_id,
        //multi_selection: false,
        // container: document.getElementById('container'),
        flash_swf_url : '/static/js/plupload/Moxie.swf',
        silverlight_xap_url : '/static/js/plupload/Moxie.xap',
        url : 'http://oss.aliyuncs.com',

//        filters: {
//            mime_types : [
//            { title : "Image files", extensions : "jpg,jpeg,gif,png,bmp"},
//            { title : "Zip files", extensions : "7z,zip,rar,xls,xlsx,doc,docx,ppt,pptx,pdf,txt,ipa,apk"},
//            ],
//            max_file_size : '60mb', //最大只能上传10mb的文件
//            prevent_duplicates : true //不允许选取重复文件
//        },

        init: {
            PostInit: function() {
                $('#' + show_id).html('');
            },

            FilesAdded: function(up, files) {
                plupload.each(files, function(file) {
                    document.getElementById(show_id).innerHTML +='<div class="up-progress" id="' + file.id + '"><p class="up-progress-p"></p></div>'
                });
                set_upload_param(uploader, '', false);
                return false;
            },
            FileFiltered: function(uploader, file) {
            for (var i in file){
            var list = ['zip']
                if (i == 'name'){
                console.log(i,":",file[i])
                var name = file[i].split('.')[1]
                if(list.toString().indexOf(name) > -1) {
                    console.log(name)
                }else{
                    for (var i in uploader.files) {
                        if (uploader.files[i].id == file.id) {
                            toremove = i;
                        }
                    }
                uploader.files.splice(toremove, 1);
                console_lc(false)
                return false;
                }
                }
            }
            },

            BeforeUpload: function(up, file) {
                set_upload_param(up, file.name, true);
            },

            UploadProgress: function(up, file) {
                $('#' + file.id).find('p').css({'width': file.percent+'%'})
                // setTimeout(function(){$('#' + file.id).remove(), 2000});
            },

            FileUploaded: function(up, file, info) {
                var url = get_uploaded_object_name(file.name)
                console.info("info=" + info)
                console.info("url=" + url)
                if (info.status == 200){
                    if(types == "pic"){
                        $("#" + show_src).attr("src", oss_upload_host + url);
                    }else{
                         $("#" + show_src).html(file.name);
                         $("#" + show_src).attr("data-src", oss_upload_host + url);
                    }

                }
            },

            UploadComplete: function(up, files){
    //            window.wxc.xcConfirm("文件传成功!", window.wxc.xcConfirm.typeEnum.success,{onOk:function(){
    //                window.location.reload();
    //            }});
            },

            Error: function(up, err) {
                if (err.code == -600) {
                    window.wxc.xcConfirm("选择的文件太大了!", window.wxc.xcConfirm.typeEnum.error,{onOk:function(){
                        window.location.reload();
                    }});
                }else if (err.code == -601) {
                    window.wxc.xcConfirm("选择的文件后缀不对!", window.wxc.xcConfirm.typeEnum.error,{onOk:function(){
                        window.location.reload();
                    }});
                }else if (err.code == -602) {
                    window.wxc.xcConfirm("这个文件已经在上传列表中!", window.wxc.xcConfirm.typeEnum.error,{onOk:function(){
                        window.location.reload();
                    }});
                }else{
                    window.wxc.xcConfirm('err-code:' + err.code +';'+  err.response, window.wxc.xcConfirm.typeEnum.error,{onOk:function(){
                        window.location.reload();
                    }});
                }
            }
        }
    });
    uploader.init();
    console.log('333333333333333333')
    console.log(uploader)
    console.log(uploader.FileFiltered)
}


function syn_edu_file_locale_course(files, oss_file_url){
        $.ajax({
            type: 'POST',
            contentType: 'application/json',
            url: '/org/syn_edu_file_oss',
            dataType : 'json',
            data : JSON.stringify({'files':files,'oss_file_url':oss_file_url}),
            success : function(response) {
                // window.location.reload();
            },error : function(response){
                window.wxc.xcConfirm("服务器出现异常，请稍后再试!", window.wxc.xcConfirm.typeEnum.error)
            }
        });
}




